<template>
  <n-modal v-model:show="registerModalVisible" @after-leave="clearForm">
    <n-card
        style="width: 600px"
        title="注册"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
    >
      <template #header-extra>
        <n-icon size="18" @click="registerModalVisible=false" style="cursor: pointer">
          <Close/>
        </n-icon>
      </template>
      <div class="login_form">
        <n-form ref="formRef" :model="modelRef" :rules="rules">
          <n-form-item path="schoolId" label="请选择学校">
            <!--            <n-input v-model:value="modelRef.schoolId" @keydown.enter.prevent />-->
            <n-select
                @update:value="schoolChangeHandle"
                v-model:value="modelRef.schoolId"
                placeholder="请选择学校"
                label-field="name"
                value-field="id"
                :options="schoolList"
            />
          </n-form-item>

          <n-form-item path="majorId" label="请选择专业">
            <!--            <n-input v-model:value="modelRef.majorId" @keydown.enter.prevent />-->
            <n-select
                v-model:value="modelRef.majorId"
                placeholder="请选择专业"
                label-field="name"
                value-field="id"
                :options="majorList"
            />
          </n-form-item>


          <n-form-item path="applyDayCount" label="请选择年限">
            <!--            <n-input v-model:value="modelRef.schoolId" @keydown.enter.prevent />-->
            <n-select
                v-model:value="modelRef.applyDayCount"
                placeholder="请选择年限"
                label-field="label"
                value-field="value"
                :options="yearList"
            />
          </n-form-item>


          <n-form-item path="name" label="请输入姓名">
            <n-input v-model:value="modelRef.name" placeholder="请输入姓名" @keydown.enter.prevent/>
          </n-form-item>

          <n-form-item path="studentNumber" label="请输入学号">
            <n-input v-model:value="modelRef.studentNumber" placeholder="请输入学号"
                     @keydown.enter.prevent/>
          </n-form-item>

          <n-form-item path="phone" label="请输入手机号">
            <n-input v-model:value="modelRef.phone" placeholder="请输入手机号"
                     @keydown.enter.prevent/>
          </n-form-item>

          <n-form-item path="password" label="密码">
            <n-input
                v-model:value="modelRef.password"
                type="password"
                placeholder="请输入密码"
                @input="handlePasswordInput"
                @keydown.enter.prevent
            />
          </n-form-item>
          <n-form-item
              ref="rPasswordFormItemRef"
              first
              placeholder="请再次输入密码"
              path="reenteredPassword"
              label="重复密码"
          >
            <n-input
                v-model:value="modelRef.reenteredPassword"
                :disabled="!modelRef.password"
                type="password"
                @keydown.enter.prevent
            />
          </n-form-item>
          <n-row :gutter="[0, 24]">
            <n-col :span="24">
              <div style="display: flex; justify-content: flex-end">
                <n-button
                    :disabled="modelRef.age === null"
                    round
                    type="primary"
                    @click="handleValidateButtonClick"
                >
                  提交注册审核
                </n-button>
              </div>
            </n-col>
          </n-row>
        </n-form>
      </div>

    </n-card>
  </n-modal>
</template>

<script setup>
import {Close} from '@vicons/ionicons5'
import {requestRegister} from "../api/user/UserApi";
import md5 from "js-md5";
import {requestSchoolApi} from "../api/school/SchoolApi";
import {requestMajorApi} from "../api/major/majorApi";

const registerModalVisible = ref(false)

/**
 * 学校发生改变
 */
const schoolChangeHandle = ()=>{
  console.log('schoolChangeHandle')
  loadMajorList()
}
const open = () => {
  registerModalVisible.value = true
}

const close = () => {
  registerModalVisible.value = false
}

/**
 * 清空表单
 */
const clearForm = () => {
  modelRef.value = {}
}

defineExpose({open, close})

function validatePasswordStartWith(rule, value) {
  return !!modelRef.value.password && modelRef.value.password.startsWith(value)
      && modelRef.value.password.length >= value.length;
}

function validatePasswordSame(rule, value) {
  return value === modelRef.value.password;
}

const rules = {
  schoolId: [
    {
      required: true,
      message: "请选择学校",
      trigger: ["change", "blur"]
    }
  ],
  majorId: [
    {
      required: true,
      message: "请选择专业",
      trigger: ["change", "blur"]
    }
  ],
  applyDayCount: [
    {
      required: true,
      message: "请选择您的专业学制",
      trigger: ["change", "blur"]

    }
  ],
  phone: [
    {
      required: true,
      message: "请输入您的手机号",
      trigger: ["input", "blur"]
    }
  ],
  name: [
    {
      required: true,
      message: "请输入您的姓名",
      trigger: ["input", "blur"]

    }
  ],
  studentNumber: [
    {
      required: true,
      message: "请输入您的学号",
      trigger: ["input", "blur"]
    }
  ],

  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["input", "blur"]
    }
  ],
  reenteredPassword: [
    {
      required: true,
      message: "请再次输入密码",
      trigger: ["input", "blur"]
    },
    {
      validator: validatePasswordStartWith,
      message: "两次密码输入不一致",
      trigger: ["input", "blur"]
    },
    {
      validator: validatePasswordSame,
      message: "两次密码输入不一致",
      trigger: ["blur", "password-input"]
    }
  ]
};
/**
 * 登录弹框
 * @type {*}
 */
const modelRef = ref({
  schoolId: null,
  majorId: null,
  name: null,
  studentNo: null,
  phone: null,
  password: null,
  reenteredPassword: null,
  applyDayCount: null
});

/**
 * 学校列表
 * @type {*}
 */
const schoolList = ref([])

/**
 * 年限
 * @type {Ref<UnwrapRef<[{label: string, value: number},{label: string, value: number},{label: string, value: number},{label: string, value: number}]>>}
 */
const yearList = ref([
  {
    value: '355',
    label: '1年'
  },
  {
    value: '710',
    label: '2年'
  },
  {
    value:'1065',
    label: '3年'
  },
  {
    value: '1420',
    label: '4年'
  }
])

/**
 * 专业列表
 * @type {*}
 */
const majorList = ref([])

/**
 * 加载学校列表
 */
const loadSchoolList = ()=>{
  requestSchoolApi().then(res=>{
    schoolList.value =  res.data.map(item=>{
      item.id = '' + item.id
      return item;
    })
  })
}

/**
 * 加载专业列表
 */
const loadMajorList = ()=>{
  requestMajorApi().then(res=>{
    res = res.data
    majorList.value = res.map(item=>{
      item.id = '' + item.id
      return item;

    })
  })
}

onMounted(()=>{
  loadSchoolList()
})

const formRef = ref(null);
const rPasswordFormItemRef = ref(null);
const handlePasswordInput = () => {
  if (modelRef.value.reenteredPassword) {
    rPasswordFormItemRef.value?.validate({trigger: "password-input"});
  }
}
const message = window.$message;

const handleValidateButtonClick = (e) => {
  e.preventDefault();
  formRef.value?.validate((errors) => {
    if (!errors) {
      // message.success("验证成功");
      requestRegister({
        ...modelRef.value,
        password:md5(modelRef.value.password)
      }).then(res => {
        //注册信息提交成功
        window.$message.success("注册信息提交成功，请等待审核")
        registerModalVisible.value = false
      })
    } else {
      console.log(errors);
      message.error("请先完善注册信息");
    }
  });
}

</script>

<style scoped>

</style>
